package file;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * BIO、NIO性能测试
 */
public class IoTest {
    @Test
    public void bioTest(){
        long begin = System.currentTimeMillis();
        InputStream in = null;
        try{
            in = new BufferedInputStream(new FileInputStream("C:\\Users\\admin\\Desktop\\UserCtrl.java"));

            byte [] buf = new byte[1024];
            int bytesRead = in.read(buf);
            while(bytesRead != -1)
            {
                for(int i=0;i<bytesRead;i++)
                    System.out.print((char)buf[i]);
                bytesRead = in.read(buf);
            }
        }catch (IOException e)
        {
            e.printStackTrace();
        }finally{
            try{
                if(in != null){
                    in.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("BIO方式读取文件用时："+(end-begin));
    }
    @Test
    public void nioTest(){
        long begin = System.currentTimeMillis();
        RandomAccessFile aFile = null;
        try{
            aFile = new RandomAccessFile("C:\\Users\\admin\\Desktop\\UserCtrl.java","rw");
            FileChannel fileChannel = aFile.getChannel();
            ByteBuffer buf = ByteBuffer.allocate(1024);

            int bytesRead = fileChannel.read(buf);

            while(bytesRead != -1)
            {
                buf.flip();
                while(buf.hasRemaining())
                {
                    System.out.print((char)buf.get());
                }

                buf.compact();
                bytesRead = fileChannel.read(buf);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(aFile != null){
                    aFile.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("NIO方式读取文件用时："+(end-begin));
    }

}
